//---------------------------------------------------------------------------------
#include <QPainter>
#include <QKeyEvent>
#include <QtDebug>
#include <QDateTime>
#include <QMouseEvent>
#include "CSceneWidget.h"
#include "CAStar.h"
#include "CAStarCaisse.h"
//---------------------------------------------------------------------------------
CSceneWidget::CSceneWidget(QWidget* parent) : QWidget(parent) { 
	map=0; 
	step=0;
	mario=CMario::getInstance();
}
//---------------------------------------------------------------------------------
void CSceneWidget::reset(void) { 
	mario->setIsMoving(false); 
	mario->setSens(CMario::tsGauche);
}
//---------------------------------------------------------------------------------
void CSceneWidget::paintEvent(QPaintEvent*) {
	QPainter painter(this);
	
	painter.setBrush(Qt::white);
	painter.setPen(Qt::white);
	painter.drawRect(rect());
	
	if(map != 0) {
		int width;
		int height;
		
		map->getSize(width, height);
		
		margeX=(size().width()-width*SPRITE_WIDTH)/2;
		margeY=(size().height()-height*SPRITE_HEIGHT)/2;
		
		map->draw(&painter, margeX, margeY, step);
	}
}
//---------------------------------------------------------------------------------
void CSceneWidget::mouseReleaseEvent(QMouseEvent* event) {
	int x, y;
	CCase *c;
	QList<CMap::EAction> actions;
	
	x=(event->x()-margeX)/SPRITE_WIDTH;
	y=(event->y()-margeY)/SPRITE_HEIGHT;
	
	c=map->getCase(x, y);
	if(c != 0) {
		int xP, yP;
				
		map->getPlayerPos(xP, yP);
		
		if(c->getCaseType() == CCase::ectVide) {
			if(c->hasCaisse()) {
				map->setSelectedCase(x, y);
			}else {
				CCase* selectedCase=map->getSelectedCase();
				if(selectedCase != 0) {
					CAStarCaisse astarCaisse(map);
					
					if(astarCaisse.pushTo(selectedCase->getX(), selectedCase->getY(), x, y, actions)) {
						emit(playerMove(actions));
					}
				}else {
					CAStar astar(map);
					
					if(astar.goTo(xP, yP, x, y, actions)) {
						emit(playerMove(actions));
					}
				}
				map->noSelectedCase();
			}
		}
	}
}
//---------------------------------------------------------------------------------
